package cc.linker.steplink.crm.merchant.service;


import cc.linker.steplink.crm.commons.RandomCodeGenerator;
import cc.linker.steplink.crm.commons.http.HttpService;
import cc.linker.steplink.crm.commons.oss.OssService;
import cc.linker.steplink.crm.merchant.dao.QrcodeDao;
import cc.linker.steplink.crm.merchanth5.dao.acs.PurchaseProcessDao;
import cc.linker.steplink.crm.response.GlobalException;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@Service
public class QrcodeService {

    @Autowired
    private QrcodeDao qrcodeDao;
    @Value("${system.scrm.wxpushurl}")
    private String wxpushurl;
    @Autowired
    private HttpService httpService;
    @Autowired
    private OssService ossService;
    @Autowired
    private PurchaseProcessDao purchaseProcessDao;


    public List<Map<String, Object>> getList(Map<String, Object> param) throws ParseException {
        List<Map<String, Object>> list = qrcodeDao.getList(param);
        if(null!=list && list.size()>0){
            Calendar now = Calendar.getInstance();
            Date nowTimeDate = now.getTime();
            String format = "yyyy-MM-dd HH:mm:ss";
            for(Map<String, Object> da:list){
                String invalidTime = da.get("invalidTime").toString();
                if(!StringUtils.isEmpty(invalidTime)){
                    Date invalidTimeDate = new SimpleDateFormat(format).parse(invalidTime);
                    if(invalidTimeDate.after(nowTimeDate)){
                        //生效中
                        da.put("status",1);
                    }else{
                        //失效
                        da.put("status",2);
                    }
                }else{
                    //永久有效
                    da.put("status",1);
                }
            }
        }
        return list;
    }

    public void saveQrcode(Map<String, Object> param) throws Exception {

        int repeatCount = qrcodeDao.getNameRepeatCount(param);
        if (repeatCount > 0) {
            throw GlobalException.build("已存在名称为'" + param.get("name") + "'的二维码");
        }
        int qrcodeType = Integer.valueOf(param.get("qrcodeType").toString());
        String orgId = param.get("orgId").toString();
        if(2 == qrcodeType){
            //设为永久二维码
            param.put("invalidTime","2099-12-31 23:59:59");
        }else{
            if(StringUtils.isEmpty(param.get("invalidTime"))){
                throw GlobalException.build("参数错误");
            }
        }
        if(!StringUtils.isEmpty(param.get("id"))){
            qrcodeDao.saveQrcode(param);
        }else{
            String qrcodeUrl = "";
            String qrcodeParam = orgId+"_"+RandomCodeGenerator.generateShortUuid();
            Map<String, Object> paramWx = new HashMap<>();
            paramWx.put("token", purchaseProcessDao.getTokenByOrgId(orgId));
            paramWx.put("val", qrcodeParam);
            if(1 == qrcodeType){
                //计算二维码有效时间
                String invalidTime = param.get("invalidTime").toString();
                String format = "yyyy-MM-dd HH:mm:ss";
                long time = new SimpleDateFormat(format).parse(invalidTime).getTime()/1000;
                long now = System.currentTimeMillis()/1000;
                long second = time-now;
                if(second <= 0){
                    second = 1;
                }
                paramWx.put("seconds", second);
                paramWx.put("action", "getStrQrcode");
            }else{
                paramWx.put("action", "getLimitQrcode");
            }
            String result = httpService.doPost(wxpushurl,JSON.toJSONString(paramWx));
            Map ret = (Map) JSON.parse(result);
            if (200 == (Integer) ret.get("errcode")) {
                Map tmpMap = (Map) ret.get("data");
                qrcodeUrl = ossService.uploadFileToOssByUrl(tmpMap.get("qrcodeurl").toString());
            }else{
                throw GlobalException.build("保存失败");
            }
            param.put("qrcodeParam", qrcodeParam);
            param.put("qrcodeUrl", qrcodeUrl);
            qrcodeDao.addQrcode(param);
        }

    }

    public Map<String, Object> getInfo(Map<String, Object> param) {
        return qrcodeDao.getInfo(param);
    }

    public boolean bindPublic(String orgId) {
        return qrcodeDao.bindPublic(orgId);
    }
}
